﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Keepo.Models;
using AlbumDesigner.Models.Types;
using Keepo.Models.Services;
using Keepo.Helpers;
using AlbumDesigner.Models.Enums;
using AlbumDesigner.Helpers;

namespace AlbumDesigner.Controllers
{
    public class PremadePagesController : Controller
    {
        private AlbumContext db = new AlbumContext();

        [CheckPermission(section = "PremadePages")]
        public ActionResult Index()
        {
            return View();
        }

        [CheckPermission(section = "PremadePages")]
        [HttpPost]
        public ActionResult GetPremadePagesList(int categoryId, int Page = 1)
        {
            //get all the images of the specified Category
            var imagesList = db.PremadePages.Where(m => m.PremadePageCategoryId == categoryId).ToList();

            var images = imagesList.Select(m => new AlbumPageExport(m)).ToList();

            //add the Paging settings to the images list
            int rowsPerPage = 12;
            int imagesCount = images.Count();
            int startIndex = (Page - 1) * rowsPerPage;
            int pagesCount = imagesCount / rowsPerPage;
            if (imagesCount % rowsPerPage > 0)
            {
                pagesCount++;
            }

            var imagesPages = images.Skip(startIndex).Take(rowsPerPage);

            return Json(new { Images = imagesPages, Pages = pagesCount });
        }

        [CheckPermission(section = "PremadePages")]
        public ActionResult GetCategoriesList()
        {
            //get all the categories
            var categoriesList = db.PremadePageCategories.ToList();

            var categories = categoriesList.Select(m => new ImageCategoryData(m)).ToList();

            return Json(categories);
        }

        [CheckPermission(section = "PremadePages")]
        public ActionResult CategoryForm(int? id)
        {
            //edit mode
            if (id != null)
            {
                var category = db.PremadePageCategories.Find(id);
                return PartialView(category);
            }
            //insert mode
            else
            {
                return PartialView();
            }
        }

        [CheckPermission(section = "PremadePages")]
        [HttpPost]
        public ActionResult AddCategory(PremadePageCategory category)
        {
            //insert this category
            db.PremadePageCategories.Add(category);
            db.SaveChanges();

            return Json(new KeyValuePair<bool, string>(true, "הקטגוריה נוספה בהצלחה."));
        }

        [CheckPermission(section = "PremadePages")]
        [HttpPost]
        public ActionResult UpdateCategory(PremadePageCategory category)
        {
            //update this category
            var existingCategory = db.PremadePageCategories.Find(category.PremadePageCategoryId);
            existingCategory.Title = category.Title;
            existingCategory.TitleHebrew = category.TitleHebrew;

            db.SaveChanges();

            return Json(new KeyValuePair<bool, string>(true, "הקטגוריה עודכנה בהצלחה."));
        }

        [CheckPermission(section = "PremadePages")]
        public ActionResult DeleteCategory(int id)
        {
            //find this category
            var category = new ImageCategoryData(db.PremadePageCategories.Find(id));

            //get all the categories as SelectList
            ViewBag.MoveToCategoryId = new SelectList(db.PremadePageCategories.Where(m => m.PremadePageCategoryId != id), "PremadePageCategoryId", "TitleHebrew");

            return PartialView(category);
        }

        [CheckPermission(section = "PremadePages")]
        [HttpPost]
        public ActionResult DeleteCategory(int categoryId, int? moveToCategoryId)
        {
            //find this category
            var category = db.PremadePageCategories.Find(categoryId);

            //get all images of category
            var categoryImages = db.PremadePages.Where(m => m.PremadePageCategoryId == categoryId).ToList();

            var message = "הקטגוריה " + category.TitleHebrew + " נמחקה בהצלחה.";

            if (moveToCategoryId == null)
            {
                //delete all the premade pages of this category
                if (categoryImages.Count > 0)
                {
                    categoryImages.ForEach(m => db.PremadePages.Remove(m));
                    db.SaveChanges();
                }
            }
            else
            {
                //move all image of category to a different specified category
                categoryImages.ForEach(m => m.PremadePageCategoryId = moveToCategoryId.Value);
                db.SaveChanges();

                message = "הקטגוריה " + category.TitleHebrew + " נמחקה והעמודים שבה הועברו לקטגוריה הנבחרת.";
            }

            //delete the category
            db.PremadePageCategories.Remove(category);
            db.SaveChanges();

            return Json(new KeyValuePair<bool, string>(true, message));
        }

        [CheckPermission(section = "PremadePages")]
        public ActionResult AddPremadePage(int categoryId)
        {
            //get all the categories as SelectList
            ViewBag.CategoryId = new SelectList(db.PremadePageCategories, "PremadePageCategoryId", "TitleHebrew", categoryId);

            //get all the album sizes as SelectList
            ViewBag.AlbumSizesList = new SelectList(db.AlbumSizes, "AlbumSizeId", "Title");

            return PartialView();
        }

        [CheckPermission(section = "PremadePages")]
        [HttpPost]
        public ActionResult AddPremadePage(AlbumPageExport image)
        {
            //add the premade page to the DB
            var premadePage = new PremadePage();
            premadePage.IsSingle = image.IsSingle;
            premadePage.AlbumSizeId = 2;
            premadePage.Title = image.Title;
            premadePage.PremadePageCategoryId = image.CategoryId;

            db.PremadePages.Add(premadePage);
            db.SaveChanges();

            return Json(premadePage.PremadePageId);
        }

        [CheckPermission(section = "PremadePages")]
        [HttpPost]
        public ActionResult UploadImage(HttpPostedFileBase file)
        {
            if (file != null)
            {
                //upload the image to the resources directory
                var directoryToSave = Server.MapPath("~/resources/images/" + file.FileName);
                file.SaveAs(directoryToSave);

                return Content(Url.Content("~/resources/images/" + file.FileName));
            }
            return Content("");
        }

        [CheckPermission(section = "PremadePages")]
        public ActionResult UpdatePremadePage(int id)
        {
            var premadePage = new AlbumPageExport(db.PremadePages.Find(id));

            return PartialView(premadePage);
        }

        [CheckPermission(section = "PremadePages")]
        [HttpPost]
        public ActionResult UpdatePremadePage(AlbumPageExport image)
        {
            //find the specified image and update its details
            var existImage = db.PremadePages.Find(image.PremadePageId);

            existImage.Title = image.Title;

            db.SaveChanges();

            return Json(new KeyValuePair<bool, string>(true, "העמוד המוכן עודכן בהצלחה."));
        }

        [CheckPermission(section = "PremadePages")]
        [HttpPost]
        public ActionResult MoveImagesToCategory(string imagesIds, int categoryId)
        {
            var images = imagesIds.Split(',');

            //loop through all the specified images
            foreach (var imageId in images)
            {
                if (!string.IsNullOrEmpty(imageId))
                {
                    //find the PremadePage and update its Category
                    var premadePage = db.PremadePages.Find(int.Parse(imageId));
                    premadePage.PremadePageCategoryId = categoryId;

                }
            }

            db.SaveChanges();

            return Json(new KeyValuePair<bool, string>(true, "העמוד המוכן הועבר בהצלחה."));
        }

        [CheckPermission(section = "PremadePages")]
        [HttpPost]
        public ActionResult DeletePremadePage(string pagesIds)
        {
            var pages = pagesIds.Split(',');

            //loop through all the specified pages
            foreach (var pageId in pages)
            {
                if (!string.IsNullOrEmpty(pageId))
                {
                    //find the PremadePage and delete it
                    var premadePage = db.PremadePages.Find(int.Parse(pageId));
                    db.PremadePages.Remove(premadePage);
                    db.SaveChanges();
                }
            }

            return Json(new KeyValuePair<bool, string>(true, "העמוד המוכן נמחק בהצלחה."));
        }

        
        // Flex
        public ActionResult GetPremadePageCategories()
        {
            using (AlbumContext db = new AlbumContext())
            {
                var categories = db.PremadePageCategories.Select(m => new { key = m.PremadePageCategoryId, english = m.Title, hebrew = m.TitleHebrew });
                return Json(categories.ToArray(), JsonRequestBehavior.AllowGet);
            }
        }

        // Flex
        [HttpPost]
        public ActionResult GetPremadePagesByCategoryId(int categoryId)
        {
            return Json(AlbumsLogic.getPremadePagesByCategoryId(categoryId));
        }

    }
}
